﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using Style.eCommerce.API.APIReferences.ComercioLibre;
using Style.eCommerce.API.Mapper;
using Style.eCommerce.API.Models;
using Style.eCommerce.API.Repositories;

namespace Style.eCommerce.API.Controllers
{
    public class StoreController : ApiController
    {

        public IRepository<Store> StoreRepository { get; set; }
        public IRepository<Product> ProductRepository { get; set; }
        public IComercioLibreClient ComercioLibreClient { get; set; }

        public StoreController()
        {
            StoreRepository = new StoreRepository();
            ProductRepository = new ProductRepository();
            ComercioLibreClient = new ComercioLibreClient();
        }

        public StoreController(IRepository<Store> storeRepository, IRepository<Product> productRepository, IComercioLibreClient comercioLibreClient)
        {
            StoreRepository = storeRepository;
            ProductRepository = productRepository;
            ComercioLibreClient = comercioLibreClient;
        }

        [AcceptVerbs("GET")]
        public HttpResponseMessage GetAllStores()
        {
            return Request.CreateResponse(StoreRepository.GetAll());
        }

        [AcceptVerbs("GET")]
        public HttpResponseMessage GetProducts(int storeId)
        {
            try
            {
                var store = StoreRepository.GetById(storeId);
                var products = ComercioLibreClient.GetSellerProducts(store.ComercioLibreId);

                return Request.CreateResponse(products.Products.Select(p => EntityMapper.Map(p)));
            }
            catch (Exception)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }            
        }

        [AcceptVerbs("POST")]
        public void ImportProducts([FromUri] int[] productsId)
        {
            var products = ComercioLibreClient.Products(productsId).Select(p => EntityMapper.Map(p));

            foreach (var p in products)
            {
                if (!ProductRepository.ExistId(p.Id))
                {
                    ProductRepository.Add(p);
                }               
            }
        }

        [AcceptVerbs("PUT")]
        public void SubcribeToImportedProducts(string url)
        {
            var products = ProductRepository.GetAll();
            var clProducts = ComercioLibreClient.Products(products.Select(l => l.Id));

            foreach (var p in clProducts)
            {
                ComercioLibreClient.UpdateProduct(p.Id, url);
                ProductRepository.Update(p.Id, EntityMapper.Map(p));                
            }
        }
    }
}
